package com.zx.mes.hyl.queue;



/**
 * 循环队列实现
 * @author huayunlong
 * @date 2018-7-12
 */
public class LoopQueue<E> implements Queue<E>{

    private int front;

    private int tail;

    private int size;

    private E[] value;

    public LoopQueue(int capacity){
        value = (E[]) new Object[capacity+1];
    }

    public LoopQueue(){
        this(5);
    }

    public boolean isEmpty(){
        return front==tail;
    }

    public int getSize(){
        return size;
    }

    public int getCapacity(){
        return value.length - 1;
    }

    @Override
    public void enqueue(E e) {

        if (((tail + 1) % value.length) == front) {
            resize(getCapacity()*2);
        }

        value[tail] = e;
        tail = (tail + 1) % value.length;
        size++;

    }


    @Override
    public void dequeue() {
        if (isEmpty()) {

        }else{
            value[front] = null;
            front = (front + 1) % value.length;
            size--;
            if (size == getCapacity() / 4 && getCapacity() != 0) {
                resize(getCapacity() / 2);
            }
        }

    }


    private void resize(int capacity) {
        E[] newData = (E[]) new Object[capacity + 1];
        for (int j = 0; j <size ; j++) {
            newData[j] = value[(j + front)%value.length];
        }
        value = newData;
        front = 0;
        tail = size;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("loopQueue: front[");
        for (int i = 0; i <value.length ; i++) {
            sb.append(value[i]);
            if (i < value.length - 1) {
                sb.append(",");
            }
        }
        sb.append("] tail  capacity:" + getCapacity() + "  size:" + getSize());
        return sb.toString();
    }
}
